package code15.io;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import java.util.List;

public class TestObject {

	public static void main(String[] args) {
		//f1();
		
		f2();
	}

	private static void f2() {
		// 反序列化
		try (
				ObjectInputStream ois = new ObjectInputStream(
						new FileInputStream("src/code15/io/users.data"));
				){
			// 一次读一个对象
			// 读和写的顺序必须一致
			User u1 = (User) ois.readObject();
			User u2 = (User) ois.readObject();
			System.out.println(u1);
			System.out.println(u2);
			List<User> list = (List<User>) ois.readObject();
			System.out.println(list);
			
			System.out.println("反序列化成功");
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	private static void f1() {
		User u1 = new User(1, "tom", 22);
		User u2 = new User(2, "jerry", 24);
		List<User> list = Arrays.asList(u1, u2);
		// 序列化
		try (
				FileOutputStream fos = new FileOutputStream("src/code15/io/users.data");
				// 对于此类的包装流等，只需要关闭外层的流即可, 内部的流就会被自动关闭
				ObjectOutputStream oos = new ObjectOutputStream(fos);
				) {
			// 一次输出一个对象
			oos.writeObject(u1);
			oos.writeObject(u2);
			oos.writeObject(list);
			// 刷新
			oos.flush();
			System.out.println("序列化成功");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
